﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using RBAC.MaHaiBo.API.DTOS;
using RBAC.MaHaiBo.API.Extensions;
using RBAC.MaHaiBo.Entity;
using RBAC.MaHaiBo.Service;
using MediatR;
using RBAC.MaHaiBo.API.Application.Command.UserCommand;
using RBAC.MaHaiBo.API.Application.Command.ProvinceCommand;
using RBAC.MaHaiBo.API.Application.Command.CityCommand;
using RBAC.MaHaiBo.API.Application.Command.CountyCommand;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Authorization;

namespace RBAC.MaHaiBo.API.Controllers
{
    /// <summary>
    /// 用户控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
   [Authorize]
    public class UserController : ControllerBase
    {
        /// <summary>
        /// 日志
        /// </summary>
        ILogger<UserController> logger;
        /// <summary>
        /// 中介者
        /// </summary>
        IMediator mediator;
        //  configuration
        IConfiguration configuration;
        IUserService User;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="logger">日志</param>
        /// <param name="mediator">中介者</param>
        public UserController(ILogger<UserController> logger,
         IMediator mediator, IUserService User, IConfiguration configuration
         )
        {
            this.logger = logger;
            this.mediator = mediator;
            this.User = User;
            this.configuration = configuration;
        }
        /// <summary>
        /// 县
        /// </summary>
        /// <returns>返回县信息列表</returns>
        [HttpGet]
        public async Task<ApiResult<List<County>>> GetCounty([FromQuery] CountyCommand request)
        {
            ApiResult<List<County>> result = new ApiResult<List<County>>();
            try
            {
                result.Data = await mediator.Send(request);

            }
            catch (Exception ex)
            {
                result.Code = -1;
                result.Message = ex.Message;
                logger.LogError("【用户控制器】 县信息列表" + ex.Message);
                throw;
            }
            return result;
        }
        /// <summary>
        /// 市
        /// </summary>
        /// <returns>返回市信息列表</returns>
        [HttpGet]
        public async Task<ApiResult<List<City>>> GetCity([FromQuery] CityCommand request)
        {
            ApiResult<List<City>> result = new ApiResult<List<City>>();
            try
            {
                result.Data = await mediator.Send(request);
            }
            catch (Exception ex)
            {
                result.Code = -1;
                result.Message = ex.Message;
                logger.LogError("【用户控制器】 市信息列表" + ex.Message);
                throw;
            }
            return result;
        }
        /// <summary>
        /// 省
        /// </summary>
        /// <returns>返回省信息列表</returns>
        [HttpGet]
        public async Task<ApiResult<List<Province>>> GetProvince()
        {
            ApiResult<List<Province>> result = new ApiResult<List<Province>>();
            try
            {
                result.Data = await mediator.Send(new ProvinceCommand());
            }
            catch (Exception ex)
            {
                result.Code = -1;
                result.Message = ex.Message;
                logger.LogError("【用户控制器】 省信息列表" + ex.Message);
                throw;
            }
            return result;
        }

        /// <summary>
        /// 添加用户信息
        /// </summary>
        /// <param name="user">要添加的用户信息</param>
        /// <returns>返回受影响行数</returns>
        [HttpPost]
        public async Task<ApiResult<int>> AddUser(UserCreateCommand request)
        {
            ApiResult<int> result = new ApiResult<int>();
            try
            {
                result.Code = await mediator.Send(request);


            }
            catch (Exception ex)
            {
                result.Code = -2;
                result.Message = ex.Message;
                logger.LogError("【用户控制器】 添加用户信息" + ex.Message);
                throw;
            }
            return result;
        }
        ///// <summary>
        ///// 批量修改用户信息
        ///// </summary>
        ///// <param name="Ids">要修改的用户编号集合</param>
        ///// <returns>返回受影响行数</returns>
        //[HttpPut]
        //public async Task<ApiResult<int>> ByUpdateUser(List<int> Ids)
        //{
        //    ApiResult<int> result = new ApiResult<int>();
        //    try
        //    {
        //        result.Code = await uSer.ByUpdateUser(Ids);
        //    }
        //    catch (Exception ex)
        //    {
        //        result.Code = -1;
        //        result.Message = ex.Message;
        //        logger.LogError("【用户控制器】 批量修改用户信息" + ex.Message);
        //        throw;
        //    }
        //    return result;
        //}

        /// <summary>
        /// 逻辑删除用户编号
        /// </summary>
        /// <param name="uid">用户编号</param>
        /// <returns>返回受影响行数</returns>
        [HttpPut]
        public async Task<ApiResult<int>> DeleteUser(UserDeleteCommand request)
        {
            ApiResult<int> result = new ApiResult<int>();
            try
            {
                result.Code = await mediator.Send(request);
            }
            catch (Exception ex)
            {
                result.Code = -1;
                result.Message = ex.Message;
                logger.LogError("【用户控制器】 批量修改用户信息" + ex.Message);
                throw;
            }
            return result;
        }
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="accountNumber">账号</param>
        /// <param name="password">密码</param>
        /// <returns>返回想要的数据信息</returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<ApiResult<string>> GeLohin([FromQuery] UserLoginCommand request)
        {
            ApiResult<string> result = new ApiResult<string>();
            try
            {

                var res = await mediator.Send(request);
                if (res!=null)
                {
                    result.Data = JwtNewString(res.uId.ToString());
                }
                else
                {
                    result.Code = -1;
                    result.Message = "账号或密码错误";
                }
              
            }
            catch (Exception ex)
            {
                result.Code= -1;
                result.Message = ex.Message;
                logger.LogError("【用户控制器】 用户登录" + ex.Message);
                throw;
            }
            return result;
        }

        private string JwtNewString(string Uid)
        {
            var signingAlogorithm = SecurityAlgorithms.HmacSha256;

            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub,Uid),
                new Claim(ClaimTypes.Role,"admin"),
                new Claim(ClaimTypes.UserData,"测试"),
            };
            var secretByte = Encoding.UTF8.GetBytes(configuration["Authentication:SecretKey"]);
            var signibgkey = new SymmetricSecurityKey(secretByte);

            var signingCerdentials = new SigningCredentials(signibgkey, signingAlogorithm);
            var Token = new JwtSecurityToken(
                issuer: configuration["Authentication:Issuer"],
                audience: configuration["Authentication:Audience"],
            claims: claims,
            notBefore: DateTime.UtcNow,
            expires: DateTime.UtcNow.AddDays(1),
            signingCerdentials
             );
            var TokenStr = new JwtSecurityTokenHandler().WriteToken(Token);
            return TokenStr;
        }


        /// <summary>
        /// 显示全部用户信息
        /// </summary>
        /// <returns>返回用户数据集合</returns>
        [HttpGet]
        public async Task<ApiResult<FenYeDTO<UserInfoDTO>>> GetUser([FromQuery]UserShowCommand request)
        {
            ApiResult<FenYeDTO<UserInfoDTO>> result = new ApiResult<FenYeDTO<UserInfoDTO>>();
            try
            {
                result.Data = await mediator.Send(request);

                var Uid = HttpContext.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
                var Rid = HttpContext.User.FindFirst(ClaimTypes.Role)?.Value;
                var Userdata = HttpContext.User.FindFirst(ClaimTypes.UserData)?.Value;
            }
            catch (Exception ex)
            {
                result.Code = -1;
                result.Message = ex.Message;
                logger.LogError("【用户控制器】 显示全部用户信息" + ex.Message);
                throw;
            }
            return result;
        }
        /// <summary>
        /// 反填用户数据信息
        /// </summary>
        /// <param name="uid">用户编号</param>
        /// <returns>返回数据信息</returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpGet]
        public async Task<ApiResult<UserInfo>> GetUserInfo([FromQuery] UserBackfillCommand request)
        {
            ApiResult<UserInfo> result = new ApiResult<UserInfo>();
            try
            {
                result.Data = await mediator.Send(request);

            }
            catch (Exception ex)
            {
                result.Code = -1;
                result.Message = ex.Message;
                logger.LogError("【用户控制器】 反填用户数据信息" + ex.Message);
                throw;
            }
            return result;
        }
        /// <summary>
        /// 修改用户信息
        /// </summary>
        /// <param name="user">修改后的数据信息</param>
        /// <returns></returns>
        [HttpPut]
        public async Task<ApiResult<int>> UpdateUser(UserUpdateCommand request)
        {
            ApiResult<int> result = new ApiResult<int>();
            try
            {
                result.Code = await mediator.Send(request);
                ;

            }
            catch (Exception ex)
            {
                result.Code = -2;
                result.Message = ex.Message;
                logger.LogError("【用户控制器】 批量修改用户信息" + ex.Message);
                throw;
            }
            return result;
        }

        //[HttpGet]
        //public IActionResult cheshi() 
        //{
        //    string li = "410928200108150034";

        //    var count = li.Todata();
        //    return Ok(count);

        //}



    }
}
